package javabasic.threads;

public class DiffInterruptStop {
    //stop方法可能造成死锁，另外stop api也停止维护，一般使用interrupt方法进行线程终止
    //调用interrupt方法后，只是通知线程应该终止了，线程并不会立马终止，如果当前线程正是TIMED_WAITING状态，
    // 执行interrupt方法会抛出interruptexception异常，并将
    //isinterrupt方法的返回值置位false
    public static void main(String[] args) throws Exception{
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int i = 0;
                try {
                    //只要线程不终止，则执行业务逻辑
                    while (!Thread.currentThread().isInterrupted()) {
                        Thread.sleep(100);
                        i++;
                        System.out.println(Thread.currentThread().getName() + "-" + Thread.currentThread().getState() + "--" + "loop " + i);
                    }
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().isInterrupted());
                    System.out.println(Thread.currentThread().getName() + "-" + Thread.currentThread().getState() + "--" + "loope " + i);
                    System.out.println("执行发生异常后的业务逻辑");
                }

            }
        };

        Thread thread = new Thread(runnable);
        System.out.println(thread.getName()+" is new ");
        thread.start();
        System.out.println(thread.getName()+" is started");
        //主线程休眠
        Thread.sleep(300);
        thread.interrupt();
        System.out.println(thread.getName()+"--"+thread.getState()+"--"+"had been interrupted");

        Thread.sleep(2000);
        System.out.println(thread.getName()+"---"+thread.getState());
        //thread.interrupt();
        //System.out.println(thread.getName()+thread.getState());


    }
}
